package com.Netty.heart.server;

import com.Netty.heart.comment.CustomHeartbeatHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * Created by thinkjoy on 2017/6/29.
 */
public class ServerHandler extends CustomHeartbeatHandler{
    public ServerHandler() {
        super("server");
    }

    /**
     * 将从客户端传来的消息显示并传回给客户端
     * @param channelHandlerContext
     * @param byteBuf
     */
    @Override
    protected void handleData(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
        byte[] data=new byte[byteBuf.readableBytes()-5];
        ByteBuf responseBuf= Unpooled.copiedBuffer(byteBuf);
        byteBuf.skipBytes(5);
        byteBuf.readBytes(data);
        String content=new String(data);
        System.out.println(name+" get content:"+content);
        channelHandlerContext.write(responseBuf);
    }

    /**
     * 读超时处理（关闭）
     * @param ctx
     */
    @Override
    protected void handleReaderIdle(ChannelHandlerContext ctx) {
        super.handleReaderIdle(ctx);
        System.err.println("---client " + ctx.channel().remoteAddress().toString() + " reader timeout, close it---");
        ctx.close();
    }
}
